package com.ygqh.baby.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ygqh.baby.ao.Message;
import com.ygqh.baby.po.YgProductLog;
import com.ygqh.baby.service.YgProductLogService;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.MailUtil;

@Component
@Aspect
public class YgProductLogAspect extends LogAspect {

	@Autowired
	private YgProductLogService ygProductLogService;
	@Autowired
	private MailUtil mailUtil;

	@Pointcut("@annotation(com.ygqh.baby.annotation.ProductLog)")
	public void controllerAspect() {
	}
	
	@AfterReturning(pointcut = "controllerAspect()", returning = "returnValue")
	public void simpleAdvice(JoinPoint jp, Message returnValue) {
		String trueName = getOperator();
		threadPool.execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					if (Message.Type.success.equals(returnValue.getType())) {
						ProductLog annotation = getAnnotation(jp, ProductLog.class);
						String description = annotation.description();
						String[] paramNames = annotation.params();
						StringBuffer params = new StringBuffer();
						params.append(jp.getSignature().getName()).append(" ");
						Object[] args = jp.getArgs();
						Long productId = null;
						if (args != null && args.length > 0 && paramNames.length > 0 && args.length == paramNames.length) {
							try {
								if (args[0] != null && !args[0].toString().equals("") && paramNames[0] != null 
										&& (paramNames[0].equals("id") || paramNames[0].equals("productId"))) {
									productId = Long.valueOf(args[0].toString());
								}
							} catch (NumberFormatException e) {
							}
							params.append("[");
							for (int i = 0; i < args.length; i++) {
								if (i != 0) {
									params.append(",");
								}
								params.append(paramNames[i]).append("=").append(args[i]==null ? "" : args[i].toString());
							}
							params.append("]");
						}
						try {
							if (productId == null) {
								productId = returnValue.getExtra() == null ? null : Long.valueOf(returnValue.getExtra().toString());
							}
						} catch (NumberFormatException e) {
							sendErrorToMail(mailUtil, "商品操作日志", jp.getSignature().getName(), ExceptionUtil.getExceptionMsg(e));
						}
						ygProductLogService.saveYgProductLog(new YgProductLog(productId, trueName, description,   
								 params.toString()));
					}
				} catch (Exception e) {
					sendErrorToMail(mailUtil, "商品操作日志", jp.getSignature().getName(), ExceptionUtil.getExceptionMsg(e));
				}
			}
		});
	}
	
}
